var _columns = [{
		title: '标识符',
		field: '标识符'
	},
	{
		title: '创建时间',
		field: 'CREATED_AT'
	},
	//			{title: '规则名称',field: '规则名称'},
	//			{title: '阈值', field: '阈值'},
	{
		title: '传感器',
		field: '传感器编号'
	},
	{
		title: '实际值',
		field: '实际值'
	},
	{
		title: '预警规则名称',
		field: '规则名称'
	},
	{
		title: '预警',
		field: '预警'
	},
]


$('.form_datetime').datetimepicker({
	format: "yyyy-mm-dd hh:ii:ss",
	language: 'zh-CN',
	todayBtn: 1,
	autoclose: 1,
	todayHighlight: 1,
	startView: 2,
	forceParse: 0,
	showMeridian: 1,
	endDate: new Date(),
});



$('.selectpicker').selectpicker('val', 'mustard');
$('.selectpicker').selectpicker('val', ['mustard', 'relish']);
$('.selectpicker').selectpicker('refresh');


var initTable = function () {
	$.ajax({
		type: 'get',
		url: '/warning_record/query_all_record_by_companyid?' + "companyId=" + label_id,
		success: function (_data) {

			$("#record_log").empty();
			// if (_data.rows.length > 0) {
			// 	//初始化表格
			// 	$('#record_log').bootstrapTable('destroy').bootstrapTable({
			// 		data: _data.rows,
			// 		cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
			// 		pagination: true, //是否显示分页（*）
			// 		sidePagination: "server", //分页方式：client客户端分页，server服务端分页（*）
			// 		pageNumber: 1, //初始化加载第一页，默认第一页
			// 		pageSize: 10, //每页的记录行数（*）
			// 		pageList: [10, 25, 50, 100], //可供选择的每页的行数（*）
			// 		showColumns: true, //是否显示所有的列
			// 		columns: _columns,
			// 		rowStyle:rowStyle,//通过自定义函数设置行样式
			// 	});
			// 	//$("#hidechartdiv").attr("style", "display:block;");
			if (_data.rows.length > 0) {
				//初始化表格
				$('#record_log').bootstrapTable('destroy').bootstrapTable({
					data: _data.rows,
					cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
					pagination: true, //是否显示分页（*）
					sidePagination: "client", //分页方式：client客户端分页，server服务端分页（*）
					pageNumber: 1, //初始化加载第一页，默认第一页
					pageSize: 10, //每页的记录行数（*）
					pageList: [10, 25, 50, 100], //可供选择的每页的行数（*）
					showColumns: true, //是否显示所有的列
					columns: _columns,
					rowStyle:rowStyle,//通过自定义函数设置行样式
				});
			} else {
				bootoast({
					message: '暂无水数据',
					position: 'top',
					type: 'warning',
					timeout: 1.5,
				});
			}

		}
	});
}


// function rowStyle(row, index) {
// 	console.log(row)
// 	if(row['预警'] == "实际值超出预警规则范围") {
// 		return {
// 			classes: 'danger'
// 		}
// 	}
// 	if(row['预警'] == '一级低限预警' || row['预警'] == '一级高限预警') {
// 		return {
// 			classes: 'warning'
// 		}
// 	}
// 	if(row['预警'] == '二级低限预警' || row['预警'] == '二级高限预警') {
// 		return {
// 			classes: 'info'
// 		}
// 	}
// 	var classes = ['active', 'success', 'info', 'warning', 'danger'];
// 	if (index % 2 === 0 && index / 2 < classes.length) {
// 		return {
// 			classes: classes[index / 2]
// 		};
// 	}
// 	return {};
// }

function rowStyle(row, index) {
	var style = {};
	// style={css:{'color':'red'}};
	// return style;
	if(row['预警'] == "实际值超出预警规则范围") {
		style={css:{'color':"black"}}
		return style
	}
	else if(row['预警'] == '一级低限预警' || row['预警'] == '一级高限预警') {
		style={css:{'color':"orange"}}
		return style
	}
	else if(row['预警'] == '二级低限预警' || row['预警'] == '二级高限预警') {
		style={css:{'color':"red"}}
		return style
	}
	else if(row['预警'] == '三级低限预警' || row['预警'] == '三级高限预警') {
		style={css:{'color':"purple"}}
		return style
	}
	else{
		style={css:{'color':"green"}}
		return style
	}
}

$(function () {
	//动态加载
	//查询所有车间
	// $.ajax({
	// 	type: 'get',
	// 	url: '/warning_record/queryworkshop',
	// 	async: false,
	// 	success: function (data) {
	// 		//拼接下拉框
	// 		for (var i = 0; i < data.length; i++) {
	// 			$("#work_id").append(
	// 				"<option value='" + data[i] + "'>" + data[i] +
	// 				"</option>");
	// 		}
	// 		$("#work_id").selectpicker("refresh");

	// 	},
	// });
	$.ajax({
		type: 'get',
		url: '/chart/queryLocationByBusinessId',
		data: {
			'businessId': label_id
		},
		dataType: 'json',
		async: false,
		contentType: "application/json; charset=utf-8",
		success: function (res) {
			let data = res.data
			$('#work_id').empty();
			for (var i = 0; i < data.length; i++) {
				$("#work_id").append(
					"<option value='" + data[i] + "'>" + data[i] +
					"</option>");
			}
			$("#work_id").selectpicker("refresh");
		},
	});
	//选用change事件，当对select 1选择option时都会及时响应2的结果
	$('#work_id').change(function () {
		//清除之前缓存数据
		$('#select_no').empty();
		$("#select_no").selectpicker("refresh");
		$('#select_type').empty();
		$("#select_type").selectpicker("refresh");
		var workshop_values = $("#work_id").val();
		if (workshop_values == null) {
			return
		}
		var workshop = new Array();
		for (var i = 0; i < workshop_values.length; i++) {
			workshop[i] = 'workshop=' + workshop_values[i];
		}
		workshop = workshop.join('&');

		techProcessId = "techProcessId=" + label_id
		//根据车间查类型
		$.ajax({
			type: 'get',
			url: '/warning_record/querysortbyworkshop?' + techProcessId + "&" + workshop,
			async: false,
			success: function (data) {
				for (var i = 0; i < data.length; i++) {
					$("#select_no").append(
						"<option value='" + data[i] + "'>" +
						data[i] + "</option>");
				}
				$("#select_no").selectpicker("refresh");
			}
		});
	});
	$('#select_no').change(function () {
		//清除之前缓存数据
		$('#select_type').empty();
		$("#select_type").selectpicker("refresh");
		var workshop_values = $("#work_id").val();
		if (workshop_values == null) {
			return
		}
		var workshop = new Array();
		for (var i = 0; i < workshop_values.length; i++) {
			workshop[i] = 'workshop=' + workshop_values[i];
		}
		workshop = workshop.join('&');
		var sort = $("#select_no").val();
		sort = 'sort=' + sort;
		//根据车间和类型查传感器编号
		techProcessId = "techProcessId=" + label_id
		$.ajax({
			type: 'get',
			url: '/warning_record/querysensorrowidbyworkshopandsort?' + techProcessId + "&" + workshop + '&' + sort,
			async: false,
			success: function (data) {
				for (var i = 0; i < data.length; i++) {
					$("#select_type").append(
						"<option value='" + data[i] + "'>" +
						data[i] + "</option>");
				}
				$("#select_type").selectpicker("refresh");
			}
		});
	});

	initTable();
});

$("#btn_return").click(function () {
	$('#page-wrapper').load('pages/technological_process.html');
})

$("#search").click(
	function (event) {

		var workshop_values = $("#work_id").val();
		var workshop = new Array();
		for (var i = 0; i < workshop_values.length; i++) {
			workshop[i] = 'workshop=' + workshop_values[i];
		}
		workshop = workshop.join('&');
		var sort = $("#select_no").val();
		sort = 'sort=' + sort;

		var sensorRowIds_values = $("#select_type").val();
		var sensorRowIds = new Array();
		for (var i = 0; i < sensorRowIds_values.length; i++) {
			sensorRowIds[i] = 'sensorRowIds=' + sensorRowIds_values[i];
		}
		sensorRowIds = sensorRowIds.join('&');
		var startTime = $("#starttime").val();
		var endTime = $("#endtime").val();
		if (workshop_values == "") {
			bootoast({
				message: '请选中车间名称',
				position: 'top',
				type: 'warning',
				timeout: 1.5,
			});
			return;
		}
		if (sort == "") {
			bootoast({
				message: '请选中设备属性',
				position: 'top',
				type: 'warning',
				timeout: 1.5,
			});
			return;
		}
		if (sensorRowIds == "") {
			bootoast({
				message: '请选中设备编号',
				position: 'top',
				type: 'warning',
				timeout: 1.5,
			});
			return;
		}
		if (startTime == "") {
			bootoast({
				message: '请选中开始时间',
				position: 'top',
				type: 'warning',
				timeout: 1.5,
			});
			return;
		}
		if (endTime == "") {
			bootoast({
				message: '请选中结束时间',
				position: 'top',
				type: 'warning',
				timeout: 1.5,
			});
			return;
		}
		startTime = 'startTime=' + startTime;
		endTime = 'endTime=' + endTime;
		company_id = 'companyId=' + label_id;
		$.ajax({
			type: 'get',
			url: '/warning_record/query_record?' +
				sensorRowIds + '&' + startTime + '&' +
				endTime + '&' + company_id,
			success: function (_data) {

				$("#record_log").empty();
				if (_data.NoRuleId.length > 0) {
					bootoast({
						message: '设备' + _data.NoRuleId + '缺少预警规则',
						position: 'top',
						type: 'warning',
						timeout: 1.5,
					});
				}
				if (_data.rows.length > 0) {
					//初始化表格
					$('#record_log').bootstrapTable('destroy').bootstrapTable({
						data: _data.rows,
						cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
						pagination: true, //是否显示分页（*）
						sidePagination: "client", //分页方式：client客户端分页，server服务端分页（*）
						pageNumber: 1, //初始化加载第一页，默认第一页
						pageSize: 10, //每页的记录行数（*）
						pageList: [10, 25, 50, 100], //可供选择的每页的行数（*）
						showColumns: true, //是否显示所有的列
						columns: _columns,
						rowStyle:rowStyle,//通过自定义函数设置行样式
					});
					let arr = _data.rows;
                    let chart_data = [];
                    chart_data = arr.map((item)=>{
                        return{
                            'CREATED_AT': item.CREATED_AT,
                            'SENSOR_ROW_ID': item.传感器编号,
                            'VALUE': item.实际值,
                            'RULE_NAME': item.规则名称,
                            'WARNING': item.预警,
                            'NAME': item.传感器名称
                        }
                    });
                    let sensorNames = [];
                    sensorNames = _data.names;
//                    console.log(sensorNames);


					//绘制折线图
					$("#water-chart").empty();
                    var renderData = Array();
                    $("#water-pie-chart").empty();
                    var pieMetaData = Array();
                    $("#water-bar-chart").empty();
                    var barData = Array();
                    var sum = 0;

                    for(var i = 0; i < chart_data.length; i++){
                        renderData[i] = {};
                        renderData[i]['CREATED_AT'] = chart_data[i]['CREATED_AT'];
                        renderData[i][chart_data[i]['NAME']] = chart_data[i]['VALUE'];

                        var label = chart_data[i]['NAME'];
                        var warning = chart_data[i]['WARNING'];
                        var flag = 0;
                        var flag2 = 0;
                        for(var j = 0; j < barData.length; j++){
                            if(barData[j]['label'] === label){
                                barData[j]['value']++;
                                flag = 1;
                                break;
                            }
                        }
                        if(flag == 0){
                            var item = {};
                            item['label'] = label;
                            item['value'] = 1;
                            barData.push(item);
                        }

                        for(var j = 0; j < pieMetaData.length; j++){
                            if(pieMetaData[j]['label'] == warning){
                                pieMetaData[j]['value']++;
                                flag2 = 1;
                                break;
                            }
                        }
                        if(flag2 == 0){
                            var item = {};
                            item['label'] = warning;
                            item['value'] = 1;
                            pieMetaData.push(item);
                        }
                    }
                    for(var j = 0; j < pieMetaData.length; j++){
                        sum += pieMetaData[j]['value'];
                    }
                    for(var j = 0; j < pieMetaData.length; j++){
                        var num = pieMetaData[j]['value'];
                        pieMetaData[j]['value'] = ((num/sum)*100).toFixed(2);
                    }
                    Morris.Line({
                        element: 'water-chart',
                        data: renderData,
                        xkey: 'CREATED_AT',
                        ykeys: sensorNames,
                        labels: sensorNames,
                        hideHover: 'auto',
                        resize: true
                    });
                    Morris.Bar({
                        element: 'water-bar-chart',
                        data: barData,
                        xkey: 'label',
                        ykeys: ["value"],
                        labels: ["数量"],
                        barRatio: 0.4,
                        xLabelAngle: 15,
                        hideHover: "auto",
                        barColors: ["#f0ad4e"]
                    });
                    Morris.Donut({
                        element: 'water-pie-chart',
                        data: pieMetaData,
                        colors: ["#f0ad4e","#3c8dbc", "#f56954", "#00a65a", "#5bc0de", "#D2691E", "#FF7F50"],
                        formatter: function(y) {
                            return y + "%";
                        }
                    });

				} else {
					$("#hidechartdiv").hide();
					bootoast({
						message: '暂无水数据',
						position: 'top',
						type: 'warning',
						timeout: 1.5,
					});
				}

			}
		});
	});